package com.pengke.pangu.global;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.pengke.pangu.common.enums.ResultCode;
import com.pengke.pangu.common.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotLoginException.class)
    public R handlerNotLoginException(NotLoginException e, HttpServletRequest request) {
        log.error("业务异常,请求地址：{},{}",request.getRequestURI(), e.getMessage());
        return R.fail(ResultCode.UNAUTHORIZED);
    }

    @ExceptionHandler(NotPermissionException.class)
    public R handlerNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        log.error("业务异常,请求地址：{},{}",request.getRequestURI(), e.getMessage());
        return R.fail(ResultCode.FORBIDDEN);
    }

    @ExceptionHandler(NotRoleException.class)
    public R handlerNotRoleException(NotRoleException e, HttpServletRequest request) {
        log.error("业务异常,请求地址：{},{}",request.getRequestURI(), e.getMessage());
        return R.fail(ResultCode.FORBIDDEN);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handlerHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("业务异常,请求地址：{},{}",request.getRequestURI(), e.getMessage());
        return R.fail(ResultCode.METHODNOTALLOWED);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handlerDuplicateKeyException(DuplicateKeyException e, HttpServletRequest request) {
        log.error("业务异常,请求地址：{},{}",request.getRequestURI(), e.getMessage());
        return R.fail(ResultCode.ERROR,"违反主外键约束，请检查数据有效性！");
    }

    @ExceptionHandler(Exception.class)
    public R handlerException(Exception e, HttpServletRequest request) {
        log.error("业务异常,请求地址：{},{}",request.getRequestURI(), e.getMessage());
        return R.fail(ResultCode.ERROR,e.getMessage());
    }

}
